<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="8" :offset="0">
                    <el-form-item label="真实姓名">
                        <el-input v-model="searchForm.realName" placeholder="真实姓名" clearable></el-input>
                    </el-form-item>
                </el-col>
               
                <el-col :span="8">
                    <el-form-item label="手机号">
                        <el-input v-model="searchForm.phone" placeholder="手机号" clearable></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData(1)">搜索</el-button>
                        <el-button @click="clickResetBtn">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 新增|刷新 -->
        <div class="flex items-center  mb-4">
            <el-button type="primary" size="small" @click="clickAddBtn(0)">新增</el-button>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="tableDataLoading" :border="true">
            
            <el-table-column prop="realName" label="真实姓名" align="center"></el-table-column>

            <el-table-column prop="roleType" label="角色类型" align="center">
                <template #default="{ row }">
                {{ transferWxUserType(row.roleType) }}
                </template>
            </el-table-column>

            <el-table-column prop="deptName" label="部门名称" align="center"></el-table-column>

            <el-table-column prop="phone" label="手机号" #default="{ row }" align="center">
                {{ row.phone }}
            </el-table-column>

            <el-table-column prop="idCard" label="身份证" #default="{ row }" align="center">
                {{ row.idCard }}
            </el-table-column>

            <el-table-column prop="email" label="邮箱"></el-table-column>

            <el-table-column prop="sex" label="性别" align="center">
                <template #default="{ row }">
                {{ transferSex(row.sex) }}
                </template>
            </el-table-column>

            <el-table-column prop="isBind" label="绑定状态" align="center">
                <template #default="{ row }">
                {{ transferWxUserBind(row.isBind) }}
                </template>
            </el-table-column>

            <el-table-column label="绑定时间" align="center">
                <template #default="{ row }">
                {{ dateFormatter(row.bindTime) }}
                </template>
            </el-table-column>

            <el-table-column prop="wechatNick" label="微信昵称" align="center"></el-table-column>

            <el-table-column prop="address" label="详细地址" show-overflow-tooltip></el-table-column>
            <el-table-column prop="remark" label="备注信息" show-overflow-tooltip></el-table-column>

            <el-table-column prop="state" label="状态" align="center">
                <template #default="{ row }">
                {{ transferWxUserState(row.state) }}
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column prop="createPersonName" label="创建人" align="center">
                <template #default="{ row }">
                {{ row.createPersonName }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" fixed="right" width="120">
                <template #default="scope">
                    <div class="flex flex-row ">
                        <el-button type="primary" size="small" text @click="clickEditBtn(scope.row)">修改</el-button>

                        <el-popconfirm title="是否要删除该部门？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="clickDeleteBtn(scope.row.id)">
                            <template #reference>
                                <el-button text type="primary" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>

        <!-- 新增 更新 抽屉 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="clickDrawerSubmitBtn" size="40%">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">

                <el-form-item required label="真实姓名" prop="realName">
                    <el-input v-model="form.realName" placeholder="真实姓名"></el-input>
                </el-form-item>

                <el-form-item required label="手机号" prop="phone">
                    <el-input v-model="form.phone" ></el-input>
                </el-form-item>

                <el-form-item label="身份证" prop="idCard">
                    <el-input v-model="form.idCard" ></el-input>
                </el-form-item>

                <el-form-item required label="角色类型" prop="roleType">
                    <el-select @change="roleTypeChange" v-model="form.roleType" placeholder="角色类型" style="width: 240px">
                        <el-option  key="0" label="工程师" value="0" />
                        <el-option  key="1" label="客户" value="1" />
                    </el-select>
                </el-form-item>

                <el-form-item label="部门" prop="deptId" v-if="isShowDept">
                    <el-cascader required v-model="form.deptId" ref="dept_el_cascader_ref" @change="handleChange_department" :props="departmentTreeProp" :options="departmentTreeData" :show-all-levels="false" popper-class="popper"/>
                </el-form-item>

                <!-- <el-form-item label="状态" prop="state">
                    <el-switch v-model="form.state" active-text="启用" active-value="1" inactive-text="禁用" inactive-value="0"/>
                </el-form-item> -->

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" ></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-switch v-model="form.sex" 
                    active-text="女" active-value="2" 
                    inactive-text="男" inactive-value="1" />
                </el-form-item>

                <!-- <el-form-item label="省/市" prop="address">
                    <el-area-select gap="8" @get-address="handleGetAdress"></el-area-select>
                </el-form-item> -->

                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="form.address" ></el-input>
                </el-form-item>

                <!-- <el-form-item label="用户等级" prop="level">
                    <el-input maxlength="1" v-model="form.level" ></el-input>
                </el-form-item> -->

                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" ></el-input>
                </el-form-item>

            </el-form>
        </FormDrawer>
    </el-card>
</template>

<script setup>

import { ref, onMounted, reactive, computed } from 'vue'
import { api_department_tree } from "~/api/departmentApi";
import { api_user_list, api_user_add, api_user_update, api_user_delete } from "~/api/userApi";
import FormDrawer from '~/components/FormDrawer.vue'
import { toast,toastWarn } from "~/composables/util"
import { useStore } from 'vuex'
import ElAreaSelect from '~/components/el-area-select.vue'
import { transferSex,transferWxUserBind,dateFormatter,transferWxUserState,transferWxUserType } from '~/utils/common.js'
import { checkPhone } from '~/utils/validate.js'


// 页面变量
const store = useStore()
const tableData = ref([]) // 列表数据
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableDataLoading = ref(false)
const isShowDept = ref(false)
const rules = {
    realName: [
      { required: true, message: '真实姓名不能为空', trigger: 'change' }
    ],
    phone: [
      { validator: checkPhone, required: true, trigger: 'change' }
    ],
    roleType: [
      { required: true, message: '角色类型不能为空', trigger: 'change' }
    ],
    deptId: [
      { required: true, message: '部门信息不能为空', trigger: 'change' }
    ],
}
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const searchForm = reactive({
    realName: "",
    phone: "",
    page: currentPage.value,
    size: limit.value,
})
const form = reactive({
    id: editId.value,
    realName: "",
    phone: "",
    roleType: "",
    deptId: null,
    email: "",
    sex: "",
    address: "",
    remark: "",
    idCard: ""
})
const formRef = ref(null)
const formDrawerRef = ref(null)
const dept_el_cascader_ref = ref(null)
const departmentTreeData = ref([])

//props
const departmentTreeProp = {
    label: 'name',
    value: 'id',
    checkStrictly : true,
    emitPath: false
}

// 生命周期
onMounted(() => {
    //加载部门字典信息
    getDepartmentTreeData()
    //加载表格数据
    getData()
    
})

//获取列表数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }

    tableDataLoading.value = true
    searchForm.page = currentPage.value
    api_user_list(searchForm)
        .then(res => {
            console.log('resp data: ', res)
            tableData.value = res?.records
            total.value = res.total
        })
        .finally(() => {
            tableDataLoading.value = false
        })
}

// 获取部门tree
function getDepartmentTreeData() {
    api_department_tree()
        .then(res => {
            departmentTreeData.value = res
        })
}

//点击重置按钮
const clickResetBtn = () => {
    searchForm.realName = ""
    searchForm.phone = ""
    getData(1)
}


// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 点击新增角色抽屉中 提交按钮
const clickDrawerSubmitBtn = () => {
    formRef.value.validate((valid) => {
        if (!valid) return
        console.log('form', form)
        formDrawerRef.value.showLoading()

        //如果是工程师，部门信息不能为空
        if(form.roleType=="0" && (form.deptId == ""||form.deptId == null)){
            toastWarn("")
        }

        const fun = editId.value ? api_user_update(editId.value, form) : api_user_add(form)

        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        }).catch(err => {

        }).finally(() => {
            formDrawerRef.value.hideLoading()
        })

    })
}

// 编辑
const clickEditBtn = (row) => {
    editId.value = row.id
    resetForm(row)

    formDrawerRef.value.open()
}

// 新增
const clickAddBtn = () => {
    //修改标记置为0
    editId.value = 0
    //默认隐藏部门
    isShowDept.value = false
    resetForm({
        realName: "",
        phone: "",
        roleType: "",
        deptId: null,
        email: "",
        sex: "",
        address: "",
        remark: "",
        idCard: ""
    })
    formDrawerRef.value.open()
}

// 删除
const clickDeleteBtn = (id) => {
    tableDataLoading.value = true
    api_user_delete(id).then(res => {
        toast("删除成功")
        getData()
    }).catch(err => {

    }).finally(() => {
        tableDataLoading.value = false
    })
}

// 获取省市区
const handleGetAdress = (data) => {
    console.log('省市区： ', data)
    form['province'] = data.code[0]
    form['city'] = data.code[1]
    console.log('province: ', formRef.value.province)
}

// 选择部门
const handleChange_department = (data) => {
    let checkedNode = dept_el_cascader_ref.value.getCheckedNodes()?.[0]
    // formRef.value.deptId = checkedNode.value
    form['deptName'] = checkedNode.label
}

// 角色改变进行是否展示部门选择
const roleTypeChange = (value) => {
    if(value == "0"){
        isShowDept.value = true
    }else{
        isShowDept.value = false
    }
}

</script>

<style>
.popper .el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 0px !important;
  right: 0px !important;
}
.popper .el-cascader-panel .el-checkbox {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 0px;
  right: 0px;
}
.popper .el-cascader-panel .el-radio__input {
  margin-left: 8px;
}
.popper .el-cascader-panel .el-checkbox__input {
  margin-top: 2px;
  margin-left: 8px;
}
.popper .el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>